package com.ruoyi.mp.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.mp.domain.MpTag;
import com.ruoyi.mp.domain.MpUser;
import com.ruoyi.mp.service.IMpAccountService;
import com.ruoyi.mp.service.IMpTagService;
import com.ruoyi.mp.service.IMpUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserBlacklistGetResult;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 公众号粉丝Controller
 *
 * @author 郎兴宇
 * @date 2024-10-07 18:42
 */
@RestController
@RequestMapping("/user")
public class MpUserController extends BaseController
{
    @Autowired
    private IMpUserService mpUserService;
    @Autowired
    private WxMpService wxService;
    @Autowired
    private IMpAccountService iMpAccountService;
    @Autowired
    private IMpTagService mpTagService;
    /**
     * 查询公众号粉丝列表
     */
    @RequiresPermissions("mp:user:list")
    @GetMapping("/list")
    public TableDataInfo list(MpUser mpUser)
    {
        startPage();
        mpUser.setAppId(iMpAccountService.selectMpAccountById(mpUser.getAccountId()).getAppId());
        mpUser.setAccountId(null);
        List<MpUser> list = mpUserService.selectMpUserList(mpUser);
        return getDataTable(list);
    }

    /**
     * 导出公众号粉丝列表
     */
    @RequiresPermissions("mp:user:export")
    @Log(title = "公众号粉丝", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MpUser mpUser)
    {
        List<MpUser> list = mpUserService.selectMpUserList(mpUser);
        ExcelUtil<MpUser> util = new ExcelUtil<MpUser>(MpUser.class);
        util.exportExcel(response, list, "公众号粉丝数据");
    }

    /**
     * 获取公众号粉丝详细信息
     */
    @RequiresPermissions("mp:user:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        AjaxResult ajax = AjaxResult.success();
        MpUser mpUser =  mpUserService.selectMpUserById(id);
        ajax.put(AjaxResult.DATA_TAG,mpUser);
// 初始化 List 避免空指针异常
        List<Long> tags = new ArrayList<>();

        // 获取 tagIds
        String tagIdsStr = mpUser.getTagIds();
        // 确保 tagIdsStr 不为空
        if (tagIdsStr != null && !tagIdsStr.trim().isEmpty()) {
            // 分割字符串并转换为 Long 类型
            String[] parts = tagIdsStr.split(",");
            for (String part : parts) {
                try {
                    long tagId = Long.parseLong(part.trim());
                    tags.add(tagId);
                } catch (NumberFormatException e) {
                    // 记录错误或抛出异常
                    System.err.println("Invalid tag ID format: " + part);
                }
            }
        }
        ajax.put("Tags",tags);
        List<MpTag> mpTags = mpTagService.selectAllMpTagList(mpUser.getAppId());
        ajax.put("TagsList",mpTags);
        return ajax;
    }

    /**
     * 新增公众号粉丝
     */
    @RequiresPermissions("mp:user:add")
    @Log(title = "公众号粉丝", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MpUser mpUser)
    {
        return toAjax(mpUserService.insertMpUser(mpUser));
    }

    /**
     * 修改公众号粉丝
     */
    @RequiresPermissions("mp:user:edit")
    @Log(title = "公众号粉丝", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MpUser mpUser) throws WxErrorException {
        mpUser.setDeleted(null);
        return toAjax(mpUserService.updateMpUser(mpUser));
    }

    /**
     * 删除公众号粉丝
     */
    @RequiresPermissions("mp:user:remove")
    @Log(title = "公众号粉丝", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(mpUserService.deleteMpUserByIds(ids));
    }


    /**
     * 获取公众号粉丝
     * @return
     */
    @RequiresPermissions("mp:user:fans")
    @Log(title = "公众号粉丝", businessType = BusinessType.OTHER)
    @GetMapping("/getFans/{ids}")
    public AjaxResult getFans(@PathVariable Long ids) throws WxErrorException, ParseException {
        String appId = this.iMpAccountService.selectMpAccountById(ids).getAppId();
        WxMpUserList wxMpUserList =wxService.switchoverTo(appId).getUserService().userList();
        List<WxMpUser> wxMpUsers =  wxService.switchoverTo(appId).getUserService().userInfoList(wxMpUserList.getOpenids());
        List<MpUser> mpUsers = new ArrayList<MpUser>();
        for (WxMpUser wxMpUser : wxMpUsers){
            MpUser mpUser = new MpUser().changeWxMpUser(wxMpUser,appId);
            mpUser.setNickname(wxMpUser.getRemark());
            mpUser.setAppId(appId);
            mpUsers.add(mpUser);
        }
        return toAjax(mpUserService.insertListMpUser(mpUsers));
    }

    /**
     * 获取公众号粉丝黑名单
     * @return
     */
    @RequiresPermissions("mp:user:getBlackFans")
    @Log(title = "更新黑名单", businessType = BusinessType.OTHER)
    @PostMapping("/getBlackFans/{ids}")
    public AjaxResult getBlackFans(@PathVariable Long ids) throws WxErrorException {
        try {
            String appId = this.iMpAccountService.selectMpAccountById(ids).getAppId();
            String nextOpenid = null;
            WxMpUserBlacklistGetResult wxMpUserBlacklistGetResult =  wxService.switchoverTo(appId).getBlackListService().getBlacklist(nextOpenid);
            List<String> openidList = wxMpUserBlacklistGetResult.getOpenidList();
            nextOpenid =  wxMpUserBlacklistGetResult.getNextOpenid(); //下次调用的开始openid
            int total = wxMpUserBlacklistGetResult.getTotal();
            int count = wxMpUserBlacklistGetResult.getCount();
            // 计算剩余需要请求的次数
            int remaining = total - count;
            while (remaining > 0 && nextOpenid != null) {
                WxMpUserBlacklistGetResult nextPageResult = wxService.switchoverTo(appId).getBlackListService().getBlacklist(nextOpenid);
                int currentCount = Math.min(remaining, count);
                openidList.addAll(nextPageResult.getOpenidList().subList(0, currentCount));
                nextOpenid = nextPageResult.getNextOpenid();
                remaining -= currentCount;
            }
            if(openidList.size() > 0){
                return toAjax(mpUserService.pushToBlacklist(openidList,appId));
            }else{
                return  toAjax(1);
            }

        }catch (WxErrorException e){
            return AjaxResult.error("获取粉丝黑名单失败");
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 拉黑公众号粉丝
     * @return
     */
    @RequiresPermissions("mp:user:blackFans")
    @Log(title = "拉黑公众号粉丝", businessType = BusinessType.OTHER)
    @PostMapping("/blackFans/{ids}")
    public AjaxResult blackFans(@PathVariable Long[] ids,Long accountId) throws WxErrorException {
        return toAjax(mpUserService.blackFans(ids,accountId));
    }

    /**
     * 取消拉黑公众号粉丝
     * @return
     */
    @RequiresPermissions("mp:user:CansleBlackFans")
    @Log(title = "取消拉黑公众号粉丝", businessType = BusinessType.OTHER)
    @PostMapping("/cansleBlackFans/{ids}")
    public AjaxResult cansleBlackFans(@PathVariable Long[] ids,Long accountId) throws WxErrorException {
        return toAjax(mpUserService.cansleBlackFans(ids,accountId));
    }
}
